/**
 * @description 技能熟练度的路由处理
 * @author yishen@mdashen.com
 */
const router = require('koa-router')()
const { Shulian } = require('../../../db/model/index')

// 获取技能熟练度-分值列表
router.get('/shulian/getlist', async (ctx, next) => {
  const { shulianList, count } = await getShuLianList()
  if (shulianList && shulianList.length > 0) {
    ctx.body = {
      error_code: 0,
      msg: '获取成功',
      count: count,
      data: shulianList,
    }
    return
  }
})
// 修改熟练度对应分值
// TODO 逻辑有些混乱，或者判断太多了，后期简化一下
router.post('/shulian/updatefenzhi', async (ctx, next) => {
  const { shulian } = ctx.request.body
  let { id, fenzhi } = ctx.request.body
  id = id - 0
  fenzhi = fenzhi - 0
  // 数值校验
  if (!id) {
    ctx.body = { error_code: 1, msg: 'id传入错误' }
    return
  }
  if (!fenzhi || fenzhi < 0) {
    ctx.body = { error_code: 1, msg: 'fenzhi传入错误' }
    return
  }
  // 通过shulian修改将，shulian字段转换为id
  const { shulianList, count } = await getShuLianList()
  if (shulian && shulian.length > 0) {
    const item = shulianList.filter((item) => {
      if (item.shulian === shulian) {
        console.log(item)
        return item
      }
    })
    id = item[0]?.id - 0
    if (!id) {
      ctx.body = {
        error_code: 1,
        msg: '修改失败，shulian字段传入错误(传入的值不存在)',
      }
      return
    }
  }
  let item = {},
    index = 0
  // 当前修改的对象 item
  shulianList.filter((item1, index1) => {
    if (item1.id === id) {
      item = item1
      index = index1
    }
  })
  // 低级熟练度分值，不能大于高级熟练度的分值
  if (index === count - 1) {
    console.log('最高级不用判断，是否大于高级熟练度分值')
    ctx.body = await updateShulian(fenzhi, id)
    return
  } else if (fenzhi - 0 >= shulianList[index + 1].fenzhi) {
    console.log(shulianList[index + 1].fenzhi)
    ctx.body = {
      error_code: 1,
      msg: '低等级分值不能大于高等级分值',
    }
    return
  }
  // 高级熟练度的分值，不能低于低级熟练度的分值
  if (index === 0) {
    console.log('最低级不用判断，是否小于低级熟练度分值')
    ctx.body = await updateShulian(fenzhi, id)
    return
  } else if (fenzhi - 0 <= shulianList[index - 1].fenzhi) {
    ctx.body = {
      error_code: 1,
      msg: '高等级分值不能小于低等级等级分值',
    }
    return
  }
  ctx.body = await updateShulian(fenzhi, id)
})

//获取熟练度以及对应分值
async function getShuLianList() {
  const res = await Shulian.findAndCountAll({
    attributes: ['id', 'shulian', 'fenzhi'],
  })
  const shulianList = res.rows.map((row) => row.dataValues)
  return { shulianList, count: res.count }
}
async function updateShulian(fenzhi, id) {
  if (!fenzhi || !id) {
    return { error_code: 1, msg: '错误，请检查传入值是否符合要求' }
  }
  fenzhi = fenzhi - 0
  id = id - 0
  try {
    var res = await Shulian.update({ fenzhi }, { where: { id } })
  } catch (error) {
    // 传入的值不符合要求，例如分值重复
    console.log(error)
    return { error_code: 1, msg: '错误，请检查传入值是否符合要求' }
  }
  if (res && res[0] === 1) {
    return { error_code: 0, msg: '修改成功' }
  } else {
    return {
      error_code: 1,
      msg: '修改失败，请检测传入的id或熟练度名称是否存在',
    }
  }
}
module.exports = router
